package com.yuanian.timingwheel.model.task.transaction;

import com.yuanian.timingwheel.model.task.base.BaseTask;
import com.yuanian.timingwheel.threadlocal.ThreadLocalEntity;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import java.io.Serializable;

/**
 * 任务执行的事务回调
 */
public class TaskTransactionCallback implements TransactionCallback<Object>, Serializable {

    private BaseTask task;

    public TaskTransactionCallback(BaseTask task) {
        this.task = task;
    }

    @Override
    public Object doInTransaction(TransactionStatus transactionStatus) {
        Object result;
        try {
            result = task.getTaskMethod().execute();
            //执行附加任务
            if (task.getAttachTaskList() != null) {
                for (BaseTask attachTask : task.getAttachTaskList()) {
                    attachTask.execute();
                }
            }
            task.getExecutionStrategy().onSuccess(task, result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            //回滚
            transactionStatus.setRollbackOnly();
            task.getExecutionStrategy().onFailure(task, e);
            return null;
        } finally {
            ThreadLocalEntity.clear();
        }
    }

    public Object doOutTransaction() {
        Object result;
        try {
            result = task.getTaskMethod().execute();
            //执行附加任务
            if (task.getAttachTaskList() != null) {
                for (BaseTask attachTask : task.getAttachTaskList()) {
                    attachTask.execute();
                }
            }
            return result;
        } catch (Exception e) {//附加任务异常，抛出给主任务逻辑去回滚事务
            throw e;
        }
    }

}
